﻿qweb.defineGlobal("mia.qweb");
mia.qweb.console = Class.create();
mia.dragdrop = mia.dragdrop || {};

Object.extend(mia.dragdrop, {
    dragstart: function(event) {
        event.dataTransfer.setData("text/plain", null);
        $('preview').hide();
    },

    dragover: function(event) {
        event.preventDefault();
        return false;
    },

    dragend: function(event) {
        var height = document.viewport.getHeight() - event.clientY ;
        localStorage.setItem("mia.qweb.console.preview_zone_size", height+ "px");
        $("resizer").style.bottom = height + "px";
        $("preview").height = height + "px";
        $('preview').show();
        event.preventDefault();
        return false;
    }
});

Object.extend(mia.qweb.console.prototype, {
    _sidebar: null,
    _actions: {},
    _content: null,
    _preview: null,
    _resizer: null,

    initialize: function () {
        this._sidebar = new Element("div").addClassName("sidebar");
        var page = new Element("div").addClassName("page");
        this._content = new Element("div").addClassName("content");
        document.body.appendChild(this._sidebar);
        page.appendChild(this._content);
        document.body.appendChild(page);
        this.setupPreview();
        qweb.api.actions.getall(null, function (result) {
            this._actions = result;
            this.renderActions();
        }.bind(this));
        Event.observe(window, "resize", function() {
            this.resizePreview();
        }.bind(this));
    },

    setupPreview: function() {
        var previewsize = localStorage.getItem("mia.qweb.console.preview_zone_size");
        this._resizer = new Element("div", { "id": "resizer", "draggable": "true" }).addClassName("resizer");
        document.body.observe("drop", mia.dragdrop.dragend);
        document.body.observe("dragover", mia.dragdrop.dragover);
        this._resizer.observe("dragstart", mia.dragdrop.dragstart);
        this._resizer.setStyle({ "width": document.viewport.getWidth() - 250 - 16 + "px" });
        document.body.appendChild(this._resizer);
        this._preview = new Element("iframe", { "id": "preview", "name": "preview" });
        document.body.appendChild(this._preview);
        this.resizePreview();
        if (previewsize != null) {
            this._resizer.setStyle({ "bottom": previewsize });
            this._preview.height = previewsize;
        } else {
            this._resizer.setStyle({"bottom": "300px"});
            this._preview.height = "300px";
        }
    },

    resizePreview: function() {
        this._resizer.setStyle({ "width": document.viewport.getWidth() - 250 - 16 + "px"});
        this._preview.width = this._resizer.getWidth() + "px";
    },

    renderActions: function () {
        Object.keys(this._actions).each(function (key, i) {
            var action = new Element("div").addClassName("action").observe("click", function () {
                this.setcontent(this.renderBinders(this._actions[key]));
                $$("div.active").each(function(e) { e.removeClassName("active") });
                action.addClassName("active");
            } .bind(this));
            this._sidebar.appendChild(action.update(this._actions[key].Name));
        } .bind(this));
        this._sidebar.appendChild(new Element("div").addClassName("action special").update("Reset actions"));
    },

    setcontent: function (content) {
        this._content.update(content);
    },

    renderBinders: function (action) {
        var form = new Element("form", { "id": "qwebForm", "target": "preview" });
        var legend = new Element("legend").update(action.Name + "<div class='action-option help' title='" + action.Help + "'></div>");
        form.appendChild(legend);
        var result = new Element("fieldset", { "id": "qwebFieldset" });
        if (null != action.Binders) {
            action = action.Binders;
            Object.keys(action).each(function(b) {
                var type = "";
                var binder = new Element("div", { "class": "action-binder" });
                binder.name = new Element("label", { "for": action[b].Name, "class": "action-name" }).update(action[b].Name);
                binder.appendChild(binder.name);
                binder.input = null;
                binder.area = null;
                var constraint = action[b].Constraint;
                if (action[b].TypeName == "System.String" && null == constraint) {
                    binder.input = new Element("input", { "name": action[b].Name}).addClassName("action-input");
                    binder.input.setAttribute("type", "text");
                    binder.area = new Element("textarea", { "name": action[b].Name, "style": "width: 286px" }).addClassName("action-input-area");
                    binder.itt = new Element("div", { "class": "action-option itt" });
                    binder.itt.observe("click", function() {
                        if (this.previous().className == "action-input") {
                            binder.input.replace(binder.area);
                            this.className = "action-option tti";
                        } else {
                            binder.area.replace(binder.input);
                            this.className = "action-option itt";
                        }
                    });
                    if (action[b].IsLargeText) {
                        binder.appendChild(binder.area);
                    } else {
                        binder.appendChild(binder.input);
                    }
                    binder.appendChild(binder.itt);
                }
                else if (action[b].TypeName == "System.String" && null != constraint) {
                    binder.input = new Element("select", { "name": action[b].Name }).addClassName("action-input");
                    Object.keys(constraint).each(function(c) {
                        binder.input.appendChild(new Element("option", { value: c }).update(constraint[c]));
                    });
                    binder.appendChild(binder.input);
                }
                else if (action[b].TypeName == "System.Boolean") {
                    binder.input = new Element("input", { "name": action[b].Name}).addClassName("action-input");
                    binder.input.setAttribute("type", "checkbox");
                    binder.input.value = true;
                    binder.appendChild(binder.input);
                }
                if (null != action[b].Required && action[b].Required == true && null != binder.input) {
                    binder.input.setAttribute("required", "required");
                    if (null != binder.area) binder.area.setAttribute("required", "required");
                    if (null != action[b].ValidatePattern) {
                        binder.input.setAttribute("pattern", action[b].ValidatePattern);
                        if (null != binder.area) binder.area.setAttribute("pattern", action[b].ValidatePattern);
                    } else {
                        binder.input.setAttribute("pattern", "[\\w\\S]+");
                        if (null != binder.area) binder.area.setAttribute("pattern", "[\\w\\S]+");
                    }
                }
                if (null != action[b].Help) {
                    binder.help = new Element("div", { "title": action[b].Help.match(/RU\s?:\s?[^;]+/) }).addClassName("action-option help");
                    binder.insert({ bottom: binder.help });
                }
                result.appendChild(binder);
            });
        } else {
            result.update("<p>No binders found</p>");
        }
        result.appendChild(new Element("input", { type: "button", value: "Options +" }).observe("click", function() {
            var param = prompt("Name of a new option");
            if (null == param) return;
            var binder = new Element("div", { "class": "action-binder" });
            binder.name = new Element("label", { "for": param, "class": "action-name" }).update(param);
            binder.input = new Element("input", { "name": param}).addClassName("action-input");
            binder.input.setAttribute("type", "text");
            binder.appendChild(binder.name);
            binder.appendChild(binder.input);
            binder.del = new Element("div", { "class": "action-option del" }).observe("click", function() {
                binder.remove();
            });
            binder.insert({ bottom: binder.del });
            if (null != $("qwebFieldset").down("p")) {
                $("qwebFieldset").down("p").remove();
            }
            $("qwebFieldset").insert({ top: binder });
        }));
        var view = new Element("select", { "id": "qwebView" }).update(
            "<option value='xml'>XML</option>" +
            "<option value='json'>JSON</option>" +
            "<option value='qview'>QVIEW</option>" +
            "<option value='bxl'>BXL</option>" +
			"<option value='string'>String</option>" +
			"<option value='md5'>MD5</option>" +
			"<option value='view'>View</option>" 
        );
        var submit = new Element("input", { "type": "button", "value": "Call →" }).observe("click", function(e) {
            var view = $("qwebView").value;
            var form = $("qwebForm");
            var url = siteroot+"/"+$$("div.action.active")[0].innerHTML.replace(".", "/")+"."+view+".qweb";
            form.setAttribute("action",url);
            form.submit();
        }.bind(this));
        result.appendChild(new Element("div", { "class": "action-binder submit" }).insert({
            top: view,
            bottom: submit
        }));
        form.appendChild(result)
        return form;
    }
});